package org.mspring.mlog.utils;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;

import org.mspring.mlog.core.ServiceFactory;
import org.mspring.platform.cache.CacheUtils;
import org.mspring.platform.cache.service.CacheService;

/**
 * 处理评论所使用到的缓存
 * 
 * @author Gao Youbo
 * @since 2013年7月5日
 */
public class CommentCacheUtils {
    /**
     * 获取评论列表缓存
     * 
     * @param fkey
     * @param ftype
     * @param page
     * @return
     */
    public static final String getCachedCommentList(String fkey, String ftype, Integer page) {
        Map<Integer, String> pagedList = getPagedList(fkey, ftype);
        if (pagedList != null) {
            return pagedList.get(page);
        }
        return null;
    }

    /**
     * 设置评论列表缓存
     * 
     * @param fkey
     * @param ftype
     * @param page
     * @param listString
     */
    public static final void setCachedCommentList(String fkey, String ftype, Integer page, String listString) {
        CacheService cacheService = ServiceFactory.getCacheService();
        Ehcache cache = cacheService.getCache(CacheService.CacheName.DEFAULT_CACHE_NAME);
        Map<Integer, String> pagedList = getPagedList(fkey, ftype);
        if (pagedList == null) {
            pagedList = new HashMap<Integer, String>();
        }
        pagedList.put(page, listString);
        // Element parent = new Element(getCacheKey(fkey, ftype), pagedList);
        // cache.put(parent);
        CacheUtils.updateValue(cache, getCacheKey(fkey, ftype), pagedList, CacheService.ONE_DAY.intValue());
    }

    /**
     * 获取缓存中保存的分页后评论列表对象
     * 
     * @param fkey
     * @param ftype
     * @return
     */
    @SuppressWarnings("unchecked")
    public static final Map<Integer, String> getPagedList(String fkey, String ftype) {
        CacheService cacheService = ServiceFactory.getCacheService();
        Ehcache cache = cacheService.getCache(CacheService.CacheName.DEFAULT_CACHE_NAME);
        Element element = cache.get(getCacheKey(fkey, ftype));
        if (element != null) {
            Serializable value = element.getValue();
            if (value != null && value instanceof Map) {
                return (Map<Integer, String>) value;
            }
        }
        return null;
    }

    /**
     * 清除评论列表缓存
     * 
     * @param fkey
     * @param ftype
     */
    public static final void clearCachedCommentList(String fkey, String ftype) {
        CacheService cacheService = ServiceFactory.getCacheService();
        Ehcache cache = cacheService.getCache(CacheService.CacheName.DEFAULT_CACHE_NAME);
        cache.remove(getCacheKey(fkey, ftype));
    }

    private static final String getCacheKey(String fkey, String ftype) {
        return ftype + "_" + fkey;
    }
}